package com.ea.modular.service.sys;




import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ea.common.Constants.UserConstants;
import com.ea.common.node.ZTreeNode;
import com.ea.common.parent.service.CrudService;
import com.ea.common.utils.CacheUtils;
import com.ea.common.utils.ToolUtil;
import com.ea.modular.dao.sys.RoleDao;
import com.ea.modular.model.sys.Role;
import com.ea.modular.utils.sys.UserUtil;


/**
 * 角色实现
 * @author jun
 *
 */
@Service
@Transactional(readOnly=true)
public class RoleService extends CrudService<RoleDao,Role>{

	@Autowired
	private RoleDao roledao;
	/**
	 * 为角色授权菜单
	 * @param roleId
	 * @param menuIds
	 * @return
	 */
	@Transactional(readOnly=false)
    public int setAuthority(String roleId,List<String> menuIds,String userId) {
		deleteAuthority(roleId);
		if(ToolUtil.isEmpty(menuIds)){
			return 1;
		}
		return roledao.setAuthority(roleId, menuIds,userId);
    }
    
    /**
	 * 删除角色授权菜单
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly=false)
    public int deleteAuthority(String roleId) {
		//先清除菜单所关联的权限缓存
		CacheUtils.remove(UserConstants.USER_PERMISSIONS);
    	return roledao.deleteAuthority(roleId);
    }
	
	/**
	 * 根据用户ID获取所关联的角色
	 * @param userId
	 * @return
	 */
	public List<String> getRoleIds(String userId){
		return roledao.getRoleIds(userId);
	}

	/**
	 * 根据角色ID组获取所关联的角色
	 * @param roleIds
	 * @return
	 */
	public Set<String> getRoleNames(List<String> roleIds){
		return roledao.getRoleNames(roleIds);
	}
	
	
	/**
	 * 根据用户ID和角色IDS获取所关联的角色
	 * @param userId
	 * @param roleIds
	 * @return
	 */
	public List<ZTreeNode> roleTreeListByUserId(List<String> roleIds){
		return roledao.roleTreeListByUserId(roleIds);
	}
	
	/**
	 * 获取所有角色树
	 * @return
	 */
	public List<ZTreeNode> roleTreeList(){
		return  roledao.roleTreeList();
	}


	
	
	/**
	 * 为用户授权角色
	 * @param roleId
	 * @param menuIds
	 * @return
	 */
	@Transactional(readOnly=false)
	public int setUserRoleAuthority(String userId,List<String> roleIds,String sessionId) {
		deleteUserRole(userId);
		if(ToolUtil.isEmpty(roleIds)){
			return 1;
		}
		return roledao.setUserRoleAuthority(userId, roleIds, sessionId);
	
	}
	
	
	/**
	 * 删除用户授权角色
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly=false)
	public int deleteUserRole(String userId) {
		//清除角色相关的缓存
		UserUtil.clearRoleCache();
		return roledao.deleteUserRole(userId);
	}

}


